<template>
  <div class="w-full h-full">
    <div v-if="stageIndex === 0" class="type-intro text-333">
      <span class="type">听后回答（共5小题；每小题2分，共10分）</span>
      <p class="mt-10px">
        <span class="intro"
          >听对话，根据所听内容口头回答问题。在听到录音提示音后，你有十秒钟的时间作答，每段对话你将听两遍</span
        >
      </p>
    </div>
    <Stem v-else :data="stem" />
    <Recorder ref="recorderRef" @error="handlerRecorderError" />
  </div>
</template>

<script>
import Stem from '@/components/question/stem/index'
import { mapState } from 'vuex'
import { generateStudentAnswer, formatQuestionStem } from '@/utils/question'
import Recorder from '@/components/recorder'
import { uploadFile } from '@/api/common'

export default {
  components: { Stem, Recorder },
  inject: ['globalData'],
  props: {},
  data() {
    return {
      actionTimer: null
    }
  },
  computed: {
    stageIndex() {
      const { stageIndex } = this.globalData.controller

      return stageIndex
    },
    currentStage() {
      return this.globalData.controller.getCurrentStage()
    },
    ...mapState(['exerciseCenter']),
    currentPractice() {
      return this.exerciseCenter.currentPractice
    },
    currentQuestion() {
      const { questions, questionIndex } = this.currentPractice

      return questions[questionIndex]
    },
    stem() {
      const { questionStem: stem } = this.currentStage

      return stem ? stem : ''
    }
  },
  created() {
    this.$on('pause', () => {
      this.$refs.recorderRef.pause()
    })
    this.$on('resume', () => {
      this.$refs.recorderRef.resume()
    })
    this.init(0)
  },
  mounted() {},
  methods: {
    init(stageIndex) {
      const {
        stem: {
          info: { question: questions }
        }
      } = this.currentQuestion

      if (!Array.isArray(questions)) return

      let stages = [
        {
          name: '题型说明',
          operateTips: '听对话，根据所听内容口头回答问题。',
          duration:
            'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_2_desc.mp3'
        }
      ]

      questions.forEach((q, index) => {
        const { ask, askaudio } = q

        const stem = formatQuestionStem({
          html: `<div><span style="font-size:0.22rem;font-weight:500">听后回答（共5小题；每小题2分，共10分）</span><p><span>听下面一段对话，回答以下小题。</span></p><p>${String.prototype.replace.call(
            ask,
            /ets_th[0-9]\s/,
            `${index + 1}.`
          )}</p></div>`,
          og: null,
          sqs: [],
          type: '英语听说-听后回答'
        })

        stages = stages.concat([
          {
            name: '播放题干',
            questionIndex: index,
            questionStem: stem,
            operateTips: '放音',
            duration: `https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_2_${
              index + 1
            }.mp3`
          },
          {
            name: '播放对话第一遍',
            questionIndex: index,
            questionStem: stem,
            operateTips: '第一遍',
            duration: askaudio
          },
          {
            name: '播放对话第二遍',
            questionIndex: index,
            questionStem: stem,
            operateTips: '第二遍',
            duration: askaudio
          },
          {
            name: '准备录音',
            questionIndex: index,
            questionStem: stem,
            operateTips: '下面，请准备录音。听到提示音后，在10秒内完成作答。',
            duration:
              'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/bj_2_ask.mp3'
          },
          {
            beforeRunAction: () => {
              this.$refs.recorderRef.stop()
            },
            name: '开始录音',
            questionIndex: index,
            questionStem: stem,
            operateTips: '提示音',
            duration:
              'https://snd-ai-assistant.oss-cn-shenzhen.aliyuncs.com/question/static/english/audio/Di.mp3'
          },
          {
            beforeRunAction: () => {
              clearTimeout(this.actionTimer)
              this.$refs.recorderRef.start()
            },
            name: '录音',
            questionIndex: index,
            questionStem: stem,
            operateTips: '录音中',
            duration: 10 * 1000,
            ignoreSpeed: true
          },
          {
            name: '停止录音',
            questionIndex: index,
            questionStem: stem,
            operateTips: '停止录音',
            duration: () => {
              if (this.$refs.recorderRef.getStatus() === 'isStop') {
                return new Promise((resolve) => {
                  this.actionTimer = setTimeout(() => {
                    resolve()
                  }, 3000)
                })
              }

              return new Promise((resolve) => {
                const loading = this.$loading({
                  lock: true,
                  text: '保存录音...',
                  spinner: 'el-icon-loading',
                  background: 'rgba(0, 0, 0, 0.5)'
                })
                // 一分钟内上传不成功关闭loading弹窗
                const timer = setTimeout(() => {
                  loading.close()
                }, 60000)
                const { localStudentAnswer } = this.currentQuestion
                const { studentAnswer } = localStudentAnswer
                const {
                  record: { id: practiceId }
                } = this.exerciseCenter.currentPractice
                const { questionIndex } = this.currentStage

                this.$refs.recorderRef.stop(async (res) => {
                  const { data, file, format } = res

                  const date = Date.now()
                  const uploadPath = `question/exercise/${practiceId}/${questionIndex}/0/${date}.${format}`
                  const formData = new FormData()
                  formData.append('file', file, `${date}.${format}`)
                  formData.append('path', uploadPath)

                  try {
                    const { data: answer } = await uploadFile(formData)
                    localStudentAnswer.studentAnswer = generateStudentAnswer({
                      anSqs: studentAnswer.anSqs,
                      anSqsIndex: questionIndex,
                      ansIndex: 0,
                      answer
                    })
                    this.currentQuestion.localStudentAnswerStatus = 1
                    resolve()
                  } catch (error) {
                    console.error(error)
                  } finally {
                    clearTimeout(timer)
                    loading.close()
                  }
                })
              })
            }
          }
        ])
        return q
      })

      this.globalData.controller.reset()
      this.globalData.controller.init(stages, stageIndex)
    },
    handlerRecorderError({ message }) {
      this.$message.error(message)
    }
  }
}
</script>

<style lang="scss" scoped></style>
